<template>
  <div style="margin: 15px" class="pay">
    <el-card style="height: 100vh">
      <div slot="header">
        <span style="
            display: flex;
            align-items: center;
            font-size: 18px;
            padding-bottom: 9px;
          ">
          <img src="@/assets/img/tuanduihuizong.png" style="width: 19px; margin-right: 5px" />
          用户组管理</span>
        <div class="xhxBox"></div>
      </div>

      <!-- <el-divider></el-divider> -->
      <!-- 按钮 -->
      <div class="mb8">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd('add')"
        >新增用户组</el-button>
        <!-- <el-button
            icon="el-icon-upload2"
             size="small"
            style="background:#F5F5F5"
            @click="handleAdd"
            >导出</el-button
          > -->
      </div>
      <!-- tab-表格 -->
      <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange" height="650"
        :header-cell-style="{
              background: '#FAFAFA',
              color: 'black',
              'font-size': 15 + 'px',
              'text-align': 'center',
            }">
        <el-table-column label="用户组名称" align="center" prop="ugName">
          <template slot-scope="scope">
            <el-tag type="success" disable-transitions>{{
              scope.row.ugName
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="人数" align="center" prop="two">
          <template slot-scope="scope">
            <span>{{ scope.row.num }}</span>
          </template>
        </el-table-column>
        <el-table-column label="固定值手续费" align="center" prop="two">
          <template slot-scope="scope">
            <span>{{ scope.row.feeFixed }}</span>
          </template>
        </el-table-column>
        <el-table-column label="百分比手续费" align="center" prop="two">
          <template slot-scope="scope">
            <span>{{ scope.row.feePercentage * 100 }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="PC开启状态" align="center" prop="two">
          <template slot-scope="scope">
            <!-- <span>{{scope.row.two}}</span> -->
            <span v-show="scope.row.two" @click="openStateChange(scope.row)" style="cursor:pointer">
              <img src="@/assets/img/hk.png" alt="" style="height: 15px">
            </span>
            <span v-show="!scope.row.two" @click="openStateChange(scope.row)" style="cursor:pointer">
              <img src="@/assets/img/hk2.png" alt="" style="height: 15px">
            </span>
            <!-- <el-switch
              @change="openStateChange(scope.row)"
              v-model="scope.row.two"
              active-color="#1890FF"
              inactive-color="#ff4949"
            >
            </el-switch> -->
          </template>
        </el-table-column>
        <el-table-column label="绑定登录主题 " align="center" prop="two">
          <template slot-scope="scope">
            <span >
            {{scope.row.landingPageIdName}}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180" /> -->
        <!-- <el-table-column label="是否默认" align="center" prop="createTime">
          <template slot-scope="scope">
            <span v-show="scope.row.ugState == 0">是</span>
            <span v-show="scope.row.ugState == 1">否</span>
          </template>
        </el-table-column> -->
        <el-table-column label="绑定项目" align="center" prop="two">
          <template slot-scope="scope">
            <span v-for="item in scope.row.data" :key="item.proId">
              <img :src="item.proLogo" style="width: 19px; height: 19px; margin-right: 5px" /></span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="loginbutton(scope.row,scope.$index)" v-hasPermi="['system:post:edit']"
              style="text-decoration: underline">绑定登录主题</el-button>
            <el-button size="mini" type="text" @click="projectButton(scope.row)" v-hasPermi="['system:post:remove']"
              style="text-decoration: underline">绑定项目</el-button>
            <el-button size="mini" type="text" @click="setUpButton(scope.row)" v-hasPermi="['system:post:remove']"
              style="text-decoration: underline">手续费</el-button>
            <el-button size="mini" type="text" @click="handleAdd(scope.row)" v-hasPermi="['system:post:edit']"
              style="text-decoration: underline">编辑</el-button>
            <el-button v-show="scope.row.ugName != '默认用户组'" size="mini" type="text" @click="handleDelete(scope.row)"
              v-hasPermi="['system:post:remove']" style="text-decoration: underline">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
      <!-- 添加或修改岗位对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="岗位名称" prop="postName">
            <el-input v-model="form.postName" placeholder="请输入岗位名称" />
          </el-form-item>
          <el-form-item label="岗位编码" prop="postCode">
            <el-input v-model="form.postCode" placeholder="请输入编码名称" />
          </el-form-item>
          <el-form-item label="岗位顺序" prop="postSort">
            <el-input-number v-model="form.postSort" controls-position="right" :min="0" />
          </el-form-item>
          <el-form-item label="岗位状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>


      <el-dialog :title="title+'选择绑定登录主题'" :visible.sync="diog" width="30%">
        <el-select v-model="value" clearable placeholder="请选择">
          <el-option v-for="item in getdata" :key="item.id" :label="item.themeName" :value="item.id">
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="diog = false">取 消</el-button>
          <el-button type="primary" @click="bingloginbutton(value)">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 设置对话框 -->
      <el-dialog :title="title + '当前用户组'" :visible.sync="setUpShow" width="30%" center>
        <el-form ref="setUpData" :model="setUpData" :rules="setUprules" size="medium" label-width="100px"
          label-position="center">
          <el-row>
            <!-- <el-col :span="18"> -->
            <el-form-item label="固定值" prop="field104">
              <div class="setUpInputBox">
                <el-input v-model.trim="setUpData.field104" placeholder="请输入数值" clearable :style="{ width: '90%' }"
                  maxlength="5" @input="MoneyDecimal">
                </el-input>
                <span style="margin-left: 5px">元</span>
              </div>
            </el-form-item>
            <el-form-item label="百分比" prop="field105">
              <div class="setUpInputBox">
                <el-input v-model.trim="setUpData.field105" placeholder="请输入数值" clearable maxlength="5"
                  :style="{ width: '90%' }" @input="MoneyDecimal">
                </el-input>
                <span style="margin-left: 5px">%</span>
              </div>
            </el-form-item>
            <!-- </el-col> -->
          </el-row>
        </el-form>
        <div slot="footer">
          <el-button @click="setUpShow = false">取消</el-button>
          <el-button type="primary" @click="handelConfirm">确定</el-button>
        </div>
      </el-dialog>
    </el-card>
    <!-- 公告弹窗 -->
    <Dialog ref="mychild" @AddAnnouncement="AddAnnouncement" :uelLocation="uelLocation" />
  </div>
</template>

<script>
import Dialog from "@/views/components/Dialog.vue";
// import { listPost, getPost, delPost, addPost, updatePost, exportPost } from "@/api/system/post";
import {
  selectbindlogin,
  selectByUserGroupList,
  deleteByUgId,
  addSetUp,
  getSetUp,
  editSetUp,updateUserGroupPcState,
  updatebindlogin,
} from "@/api/base/index.js";
import { getIdentityAndTopId, getInfo } from "@/api/login.js";
import {updateUserGroup} from "@/api/system/UserGroup.js"
export default {
  name: "Post",
  data() {
    return {
        bindloginsindex:0,

      bindlogins:{},
      getdata:[],
        options:[],
        value:'',

        diog:false,


      //转换为百分比的金额
      moneyData: "",
      userId: "",
      //设置弹窗
      setUpShow: false,
      setUpData: {
        field101: "FIXED",
        field104: undefined,
        field105: undefined,
        id: undefined,
        ugId: undefined,
      },
      setUprules: {
        field101: [
          {
            required: true,
            message: "费率模式不能为空",
            trigger: "change",
          },
        ],
        field104: [
          {
            required: true,
            message: "请输入数值",
            trigger: "change",
          },

          {
            pattern: /^[0-9]*$/,
            message: "格式错误",
            trigger: "change",
          },
        ],
        field105: [
          {
            required: true,
            message: "请输入数值",
            trigger: "change",
          },
          {
            pattern: /^99$|^([0-9]{0,2})(\.\d{0,3})?$/,
            message: "格式错误,不能大于等于100小于0",
            trigger: "change",
          },
          {
            pattern:
              /(^[0-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "格式错误",
            trigger: "change",
          },
        ],
      },
      field101Options: [
        {
          label: "固定值",
          value: "FIXED",
        },
        {
          label: "百分比",
          value: "PERCENTAGE",
        },
      ],
      //公告弹窗
      uelLocation: "",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        postName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" },
        ],
        postCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" },
        ],
        postSort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.loading = false;
    this.getList();
    // this.getDicts("sys_normal_disable").then(response => {
    //   this.statusOptions = response.data;
    // });
  },
  async mounted() {
    //获取是租户还是用户还是平台
    const { data } = await getIdentityAndTopId();
    //公告弹窗
    if (data.identity == "用户") {
      this.AddAnnouncement();
    }
    const res = await getInfo();
    console.log(res, "用户信息");
    if (res.code == 200) {
      this.userId = res.user.userId - 0;
    }
  },
  components: { Dialog },
  methods: {
    
    //开启关闭按钮
   async openStateChange(row){
      console.log(row,'55')
      let param={
        two:1,
        ugId:row.ugId
      }
          // null 和 1开启   0是关闭
          if(row.two){
            param.two=0;
          }else{
             param.two=1;
          };
            // console.log(param,'+++');
      const data=await updateUserGroupPcState(param);
      console.log(data,'+++');
      if(data.code==200){
          this.$message({
          message: '操作成功!',
          type: 'success'
        });
        this.getList()
      }else{
         this.$message.error(data.msg);
      }
    // two 
    },
    // 设置确定按钮
    handelConfirm() {
      this.$refs["setUpData"].validate(async (valid) => {
        if (valid) {
          let param = {};
          let banfenbi = this.setUpData.field105 / 100;
          console.log(banfenbi, "55");
          //有id就是修改 无ID就是新增
          if (this.setUpData.id) {
            param = {
              feeFixed: this.setUpData.field104, //元
              feePercentage: banfenbi, //%
              tenantId: this.userId, //租户ID
              userGroupId: this.setUpData.ugId, //用户组ID
              id: this.setUpData.id,
            };
            const addData = await editSetUp(param);
            if (addData.code == 200) {
              this.msgSuccess("提交成功!");
              this.setUpShow = false;
                this.getList();
            } else {
              this.$message.error("操作失败!");
            }
          } else {
            param = {
              feeFixed: this.setUpData.field104, //元
              feePercentage: banfenbi, //%
              tenantId: this.userId, //租户ID
              userGroupId: this.setUpData.ugId, //用户组ID
            };
            const addData = await addSetUp(param);
            if (addData.code == 200) {
              this.msgSuccess("提交成功!");
              this.setUpShow = false;
                this.getList();
            } else {
              this.$message.error("操作失败!");
            }
          }
        }
      });
    },
    // 设置
    async setUpButton(row) {
      console.log(row, "设置");
      this.title = row.ugName;
      this.setUpData.ugId = row.ugId;

      const data = await getSetUp({
        tenantId: this.userId,
        userGroupId: row.ugId - 0,
      });
      console.log(data, "获取设置");
      if (data.code == 200) {
        if (data.data) {
          this.setUpData = {
            field104: data.data.feeFixed,
            field105: data.data.feePercentage * 100,
            id: data.data.id,
            ugId: data.data.userGroupId,
          };
        } else {
          this.setUpData = {
            field104: 0,
            field105: 0,
            ugId: row.ugId,
          };
        }
        // this.moneyData = data.data.fee;
      }
      this.setUpShow = true;
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      selectByUserGroupList().then((res) => {
        console.log(res, "列表");
        res.data.forEach(item=>{
            // null 和 1开启   0是关闭
          if(item.two!=0){
            item.two=true;
          }else{
             item.two=false;
          }
        });
       this.postList = res.data;
        this.loading = false;
      });
    },
    MoneyDecimal() {
      if (this.setUpData.field101 == "PERCENTAGE") {
        this.moneyData = this.setUpData.field105 / 100;
      } else {
        this.moneyData = this.setUpData.field104;
      }
    },

    //公告弹窗
    AddAnnouncement() {
      //传递子组件当前的路由；然后调用子组件的事件函数
      this.uelLocation = window.location.pathname.slice(1);
      this.$refs.mychild.gitData();
    },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 0,
        status: "0",
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮和编辑按钮共用 */
    handleAdd(row) {
      console.log(row, "点击了编辑");
      if (row === "add") {
        // localStorage.removeItem('param');
        localStorage.param = JSON.stringify({ ugId: "" });
        localStorage.code = 0;
      } else {
        localStorage.param = JSON.stringify(row);

        localStorage.code = 1;
      }
      // this.$router.push("/base/addindex");
        this.$router.push({
          path: '/base/addindex',
          query: {
            name: row.ugName
          }
        })
      // this.reset();
      // this.open = true;
      // this.title = "添加岗位";
    },
    //绑定登录
    async loginbutton(row,index){
      this.bindloginsindex = index
      this.bindlogins  = this.postList[index]
      console.log(row, "点击了绑定登录");
              this.diog = true
              this.value = row.landingPageIdName
              // console.log(row.uId,"用户id")
            let param ={
                tenantId: row.uId,
                userGroupId:row.ugId
            }

              // console.log(param,"用户id")

          selectbindlogin(
              param
          )
          .then((res)=>{
            if(res.code == 200){
              this.getdata = res.data
               console.log(this.getdata)
            }
          })
          .catch(err=>{
            console.log(err)
          })
    },
    //绑定登录确认按钮
    async bingloginbutton(landingPageId){
              this.diog = false
              console.log(landingPageId,this.bindlogins)
              // this.bindlogins.landingPageId = landingPageId
              //执行修改函数
              let param ={
                id:landingPageId,
                tenantId:this.bindlogins.uId,
                userGroupId:this.bindlogins.ugId
                
            }
            updatebindlogin(param)
            .then((res)=>{
                  if(res.code == 200){
                    this.$message({
                      message: "修改成功",
                      type: "success",
                        });
                    this.getList()
                  }
              })
            .catch(err=>{
              console.log(err)
            })
              

    },
    /** 绑定项目按钮 */
    projectButton(row) {
      console.log(row, "点击了编辑");
      sessionStorage.setItem("BindProId", JSON.stringify(row.data));
      this.$router.push({
        path: "/base/Bindproject",
        query: {
          ugId: row.ugId,
          ugName: row.ugName,
          inputShow:1
        },
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.postId != undefined) {
            updatePost(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPost(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      console.log(row,'222')
      const postIds = row.postId || this.ids;
      const data = await this.$confirm(
        '是否确认删除"' + row.ugName + '"的数据项?',
        "",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      );
      if (data == "confirm") {
        deleteByUgId({ ugId: row.ugId }).then((res) => {
          console.log(res, "结果");
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getList();
          }
        });
      } else {
      }
      console.log(data, "66666666");
      // .then(()=> {
      //     console.log(row, "点击了确定");
      //     deleteByUgId({ ugId: row.ugId }).then((res) => {
      //       console.log(res, "结果");
      //       if (res.code == 200) {
      //         this.getList();
      //       }
      //     });

      // })
      //   .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有岗位数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportPost(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped lang="scss">
// 弹窗屏幕居中
 ::v-deep .el-dialog__wrapper {
   display: flex;
   justify-content: center;
   align-items: center;
}

// ::v-deep .element.style {
//      margin-top: none; 
//     // width: 500px;
// }
::v-deep .el-dialog:not(.is-fullscreen) {
  // margin-top: 30vh !important;
  margin-top: 0vh !important;
  //  border: 1px red solid;
}

.xhxBox {
  height: 5px;
  border-top: 1px #eee solid;
  margin-top: 8px;
}
// .setUpInputBox {
//   // border: 1px red solid;
// }
.mb8 {
  /* border: 1px red solid; */
  margin-bottom: 10px;
}
.exportButton {
  display: flex;
  justify-content: flex-end;
}
.el-form-item__label {
  font-weight: 500;
}
</style>


<style>

.pay .el-date-editor .el-range-separator {
  width: 15%;
}
.pay .pay-item:not(:last-child) {
  border-right: 1px solid #f0f0f0;
}
.pay .el-card__body {
  height: 100%;
}

.pay .pay-item {
  width: 25%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.pay .pay-item .pay-value {
  font-size: 24px;
  font-weight: bold;
}

.pay .pay-item .pay-value span {
  font-size: 10px;
  margin-right: -5px;
}

.pay .pay-item .value-color {
  color: #3a77f6;
}

.pay .pay-item .pay-label {
  font-size: 11px;
  margin-top: 10px;
}

.pay .el-divider--horizontal {
  background: #f0f0f0;
}

.pay .el-card__header {
  margin: 0 20px;
  padding-left: 0px;
  border: none;
}

.pay .el-tabs__nav-wrap::after {
  height: 0;
}
</style>